package stardust.product.utils.transmit.auto;

import java.io.IOException;
import java.net.Socket;
import stardust.core.io.IOUtils;
import stardust.core.network.NetworkSessionInputStream;
import stardust.core.network.NetworkSessionOutputStream;
import stardust.core.network.TCPNetworkSession;
import stardust.core.network.protocol.http.HttpRequestMeta;
import sun.misc.BASE64Decoder;

public class HTTPAuthentication
{
  /*
  reqMeta.getRequest()
  */
  public static boolean doAuthenticate(HttpRequestMeta reqMeta, Socket socket) throws IOException
  {
    String authInfo = reqMeta.getOthers().get("Proxy-Authorization");
    
    if (authInfo != null)
    {
      if (authInfo.startsWith("Basic "))
      {
        authInfo = authInfo.substring("Basic ".length());
        authInfo = new String(new BASE64Decoder().decodeBuffer(authInfo));
        
        if (authInfo.indexOf(':') != -1)
        {
          String[] authInfoBlock = authInfo.split(":", 2);
          String username, password;
          
          username = authInfoBlock[0];
          password = authInfoBlock[1];
          
          if (Authenticator.getUsername().equals(username) && Authenticator.getPassword().equals(password))
          {
            return true;
          }
          else
          {
            System.err.println("error in auth [" + authInfo + "]");
          }
        }
      }
    }
    
    return HTTPAuthentication.forceAuthenticate(reqMeta, socket);
  }
  
  public static boolean forceAuthenticate(HttpRequestMeta reqMeta, Socket socket) throws IOException
  {
    TCPNetworkSession client = new TCPNetworkSession(socket);
    NetworkSessionInputStream inputStream = new NetworkSessionInputStream(client);
    NetworkSessionOutputStream outputStream = new NetworkSessionOutputStream(client);
    
    byte[] message =
    (
      "HTTP/1.1 401 Unauthorised\r\n" +
      "WWW-Authenticate: Basic realm=\"" + Authenticator.getRealm() + "\"\r\n" + 
      "\r\n" +
      "Unauthorised"
    ).getBytes();
    outputStream.write(message);
    
//    reqMeta = HttpRequestMeta.parse(inputStream);
    
    return false;
  }
  
}
